//使用过滤器对添加用户的请求进行拦截，判断是否是未登录状态(使用Session记录登录状态)

package web;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取 Session域中的login值
        HttpSession session = request.getSession();
        String login = (String) session.getAttribute("login");
        //判断非空即可放行 addUser 否则跳转到登录页面
        if(login != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            ((HttpServletResponse) servletResponse).sendRedirect("/Homework/index.html");
        }
    }

    @Override
    public void destroy() {

    }
}
